// import { Toast } from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'
import { getLocalToken } from '@/utils/local.js'
import { auInfo } from '@/api/authentication.js'
import store from '@/store/index.js'
import { Dialog } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    alias: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/home',
    component: () => import('@/views/home/home.vue'),
    redirect: '/home/my',
    children: [
      {
        path: 'enterprise',
        component: () => import('@/views/home/enterprise/enterprise.vue')
      },
      {
        path: 'find',
        component: () => import('@/views/home/find/find.vue')
      },
      {
        path: 'my',
        component: () => import('@/views/home/my/my.vue'),
        meta: {
          needLogin: true
        }
      },
      {
        path: 'question',
        component: () => import('@/views/home/question/question.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // console.log(to)
  // console.log(from)
  if (!to.meta.needLogin) {
    // console.log(111)
    // console.log(store)
    // console.log(store.state.islogin)
    next()
  } else {
    // console.log(store.state.islogin)
    if (store.state.islogin) {
      next()
    } else {
      // console.log(getLocalToken('token'))
      if (getLocalToken('token')) {
        // console.log(1111111111)
        auInfo()
          .then(res => {
            // console.log(res)
            // console.log(111)
            store.commit('setUserinfo', res.data.data)
            store.commit('setUserLogin', true)
            next()
          })
          .catch(err => {
            // console.log(222)
            console.log(err)
            router.push('/login')
          })
      } else {
        Dialog.confirm({
          title: '题型',
          message: '该模块需登录才能访问，是否登录？'
        })
          .then(() => {
            // on confirm
            router.push('/login')
          })
          .catch(() => {
            // on cancel
            // router.push(from.path)
          })
      }
    }
  }
})

export default router
